package com.jiaoyou.baojian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jiaoyou.baojian.MainActivity;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.agora.AgoraHelper;
import com.jiaoyou.baojian.constvalue.ConstValue;
import com.jiaoyou.baojian.entity.CallResponse;
import com.jiaoyou.baojian.entity.response.LoginResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.Utils;
import com.squareup.otto.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.phonenum)
    EditText phonenum;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.left_button)
    ImageView leftButton;
    @BindView(R.id.header_title)
    TextView headerTitle;
    @BindView(R.id.right_button)
    ImageView rightButton;
    @BindView(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @BindView(R.id.forget_pwd)
    TextView forgetPwd;
    @BindView(R.id.code_login)
    TextView codeLogin;
    @BindView(R.id.agree)
    CheckBox agree;
    @BindView(R.id.law)
    TextView law;

    private String mob;
    private String pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mob = bundle.getString("mobile");
            pwd = bundle.getString("password");
        }

        if (!TextUtils.isEmpty(mob) && !TextUtils.isEmpty(pwd)) {
            phonenum.setText(mob);
            password.setText(pwd);
            //自动登录
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    onViewClicked(login);
                }
            }, 500);
        }

        needOtto();
        setTitle("登录");
    }

    @Override
    public int getContentView() {
        return R.layout.activity_login;
    }

    @OnClick({R.id.login, R.id.forget_pwd, R.id.code_login, R.id.law})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.law:
                startActivity(UserLawActivity.class);
                break;
            case R.id.login:
                if(!agree.isChecked()){
                    toast("您必需同意用户协议，才能登录使用该软件");
                    return;
                }
                if (TextUtils.isEmpty(mob) || TextUtils.isEmpty(pwd)) {
                    mob = phonenum.getEditableText().toString();
                    pwd = password.getEditableText().toString();
                }
                if (TextUtils.isEmpty(mob) || TextUtils.isEmpty(pwd)) {
                    toast("帐号密码不能为空");
                    return;
                }
                if (mob.startsWith("177")) {
                    toast("不支持虚拟号段");
                    return;
                }
                waiting("登录中...");
                Api.getInstance().login(mob, pwd, new BaofangCallback<LoginResponse>() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        stopWaiting();
                        toast(t.getLocalizedMessage());
                    }

                    @Override
                    public void onSuccess(LoginResponse response) {
                        getACache().put(LoginResponse.TAG, new Gson().toJson(response));
                        final String account = getLoginResponse().user.id + "";
                        AgoraHelper.getInstance().agoraAPI.login(ConstValue.AGORA_APPID, account, Utils.getAgoraToken(account), 0, "");
//                        Api.getInstance().getLoginKey(account, new BaofangCallback<CallResponse>() {
//                            @Override
//                            public void onFailure(Call call, Throwable t) {
//                                stopWaiting();
//                                toast(t.getLocalizedMessage());
//                            }
//
//                            @Override
//                            public void onSuccess(CallResponse res) {
//                                AgoraHelper.getInstance().agoraAPI.login(ConstValue.AGORA_APPID, account, res.agoraSignalingKey, 0, "");
//                            }
//                        });

//                        //登录成功，无视agora的登录状态了，因为有时候收不到callback，很奇怪
//                        stopWaiting();
//                        toast("登录成功");
//                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(intent);
                    }
                });
                mob = "";
                pwd = "";
                break;
            case R.id.forget_pwd:
                toast("忘记密码");
                break;
            case R.id.code_login:
                startActivity(VerifyCodeLoginActivity.class);
                break;
        }
    }

    @Subscribe
    public void onEvent(String event){
        if(Event.AGORA_LOGIN_SUCCESS.equals(event)){
            //agora登录成功
            stopWaiting();
            toast("登录成功");
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if(Event.AGORA_LOGIN_ERROR.equals(event)){
            //agora登录失败
            toast("登录失败，请检查网络重试");
            stopWaiting();
        }
    }
}
